package com.heima.wemedia.builder;

import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import org.springframework.beans.BeanUtils;

import java.util.Date;

public class ArticleDtoBuilder {
    private WmNews wmNews;
    private WmChannelMapper wmChannelMapper;
    private WmUserMapper wmUserMapper;

    private ArticleDto articleDto = new ArticleDto();

    public ArticleDtoBuilder(WmNews wmNews, WmChannelMapper wmChannelMapper, WmUserMapper wmUserMapper) {
        this.wmNews = wmNews;
        this.wmChannelMapper = wmChannelMapper;
        this.wmUserMapper = wmUserMapper;
    }

    public ArticleDtoBuilder buildBeanCopy() {
        BeanUtils.copyProperties(wmNews, articleDto);

        return this;
    }

    public ArticleDtoBuilder buildAuthor() {
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            articleDto.setAuthorId(wmUser.getId());
            articleDto.setAuthorName(wmUser.getName());
        }

        return this;
    }

    public ArticleDtoBuilder buildChannel() {
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            articleDto.setChannelId(wmChannel.getId());
            articleDto.setChannelName(wmChannel.getName());
        }

        return this;
    }

    //构建基本信息到dto
    public ArticleDtoBuilder buildBasic() {
        articleDto.setLayout(wmNews.getType());
        articleDto.setCreatedTime(new Date());
        articleDto.setCollection(0);
        articleDto.setComment(0);
        articleDto.setViews(0);
        articleDto.setLikes(0);
        if (wmNews.getArticleId() != null) {
            articleDto.setId(wmNews.getArticleId());
        }

        return this;
    }

    public ArticleDto builder() {
        return articleDto;
    }

}
